package com.zzyy.study.test;

import com.deepoove.poi.XWPFTemplate;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther zzyy
 * @create 2024-10-19 21:36
 */
public class Java2Word
{
    public static void main(String[] args) throws IOException
    {

        read();

    }

    private static void read() throws IOException
    {
        XWPFDocument xwpfDocument = new XWPFDocument(new FileInputStream(new File("D:\\44\\1.docx")));

        XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(xwpfDocument);


        System.out.println(xwpfWordExtractor.getText());
    }

    /**
     * TDO模式：Template + data-model = output
     * @throws IOException
     */
    private static void Java_WriteTo_WordDoc()
    {
        //模板中需要填充的数据
        Map<String, Object> model = new HashMap<>();
        model.put("userName", "z3");
        model.put("age",40);
        model.put("description", "阳哥云自习室");

        //模板文件
        String templatePath = "D:\\44\\template.docx";
        //模板 + 数据，合并后产生的目标文件的存放的地址
        String outFile = "D:\\44\\1.docx";
        //通过word模板引擎，将模板和数据进行组合，生成新的文件
        XWPFTemplate xwpfTemplate = XWPFTemplate.compile(templatePath).render(model);
        try
        {
            xwpfTemplate.writeToFile(outFile);
            xwpfTemplate.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
